//
//  AdoptDetailViewController.m
//  PigMarket
//
//  Created by mac on 2019/4/8.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "AdoptDetailViewController.h"
#import "PigHeaderView.h"
#import "PigPayFooterView.h"
#import "OrderViewController.h"
#import "BuyPigViewController.h"
#import "BuyPigCell.h"

@interface AdoptDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 leftTitleArr
 */
@property (nonatomic , strong) NSArray *leftTitleArr;

/**
 header
 */
@property (nonatomic , strong) PigHeaderView *headerView;
/**
 尾视图bg
 */
@property (nonatomic , strong) PigDetailFooterView *footerView;
/**
 所有数据数组
 */
@property (nonatomic , strong) AdoptDetailList *dataModel;
/**
 头部图片视频数组
 */
@property (nonatomic , strong) NSMutableArray *headImgArr;
/**
 套餐数组
 */
@property (nonatomic , strong) NSMutableArray *trusteePriceArr;

@end

@implementation AdoptDetailViewController


#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - init method
- (void)setUpView {
    [self initNav];
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initNav {
   // [[NavigationBarManager sharedInstance] setupNavigationBarClear:self.navigationController];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"adopt_adoptdetail_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backTapped)];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"adopt_adoptdetail_share"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(shareTapped)];
}
- (void)initView {

    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(-TopBarHeight, 0, 0, 0));
    }];
}

- (void) initAction {
    //保存数值，区分小猪托管费用  仔猪是否默认选择
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setValue:@"NO" forKey:@"pigTrusteeIsSelect"];
}

- (void)initData {
    self.leftTitleArr = @[@[@{@"icon":@"",@"title":@"托管阶段",@"tips":@"可多选"}],
                          @[@{@"icon":@"",@"title":@"",@"tips":@""}]];
    
    [self dataRequest];
}

#pragma mark - delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 620;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 110;
}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    self.headerView = [[PigHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 620)];
//    self.headerView.backgroundColor = [UIColor globalBackgroundColor];
//    self.headerView.headerDataArr = self.headImgArr;
//    self.headerView.dataModel = self.dataModel;
//    return self.headerView;
//}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    self.footerView = [[PigDetailFooterView alloc] init];
    self.footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 110);
    [self.footerView.freeAdoptBtn addTarget:self action:@selector(freeAdoptTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView.orderBtn addTarget:self action:@selector(orderAdoptTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView.adoptBtn addTarget:self action:@selector(adoptTapped) forControlEvents:UIControlEventTouchUpInside];
    return self.footerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        
        int count = (int)self.trusteePriceArr.count / 3;
        if (self.trusteePriceArr.count % 3 > 0) {
            count += 1;
        }
        return 120 * count + 50;
    }else {
        return 42;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        TrusteeCell *cell = [TrusteeCell cellWithTrusteeTableView:tableView];
        cell.userInteractionEnabled =NO;
        [cell configCellWithDataArr:self.trusteePriceArr type:TrusteeTypeUnAdopted];
        return cell;
    }else {
        BuyPigCell *cell = [BuyPigCell cellWithTableView:tableView];
        [cell configCellWithLeftTitleDic:self.leftTitleArr[indexPath.section][indexPath.row] indexPath:indexPath];
        return cell;
    }
    return nil;
}

#pragma mark - target action
//返回
- (void)backTapped {
    [self.navigationController popViewControllerAnimated:YES];
}
//分享
- (void)shareTapped {
    
}
//免费领养
- (void)freeAdoptTapped {
    if (![self isAgreeAdoptAgreement]) {
        return;
    }
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    
    PayParam *param = [[PayParam alloc] init];
    param.adoptType = @(UnAdoptTypeFree);
    param.tribeId = tribeId;
    param.pigId = pigId;
    param.memberId = memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] payWithParam:param] subscribeNext:^(Pay * _Nullable x) {
        @strongify(self);
        [self toastWithContent:@"免费试养成功，等待审核"];
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
    
}
//99预定
- (void)orderAdoptTapped {
    if (![self isAgreeAdoptAgreement]) {
        return;
    }

    OrderViewController *orderVC = [[OrderViewController alloc] init];
    orderVC.detailModel = self.dataModel;
    [self.navigationController pushViewController:orderVC animated:YES];
}
//立即领养
- (void)adoptTapped {
    if (![self isAgreeAdoptAgreement]) {
        return;
    }
    BuyPigViewController *buyVC = [[BuyPigViewController alloc] init];
    buyVC.detailModel = self.dataModel;
    [self.navigationController pushViewController:buyVC animated:YES];
}
#pragma mark - private method
- (void)dataRequest {
    NSNumber *tribeId = [UserInfoDataProvider sharedInstance].userInfo.tribeId;
    NSNumber *pigId = [UserInfoDataProvider sharedInstance].userInfo.pigId;

    @weakify(self);
    [[[PigMarketApi sharedInstance] adoptDetailWithPigId:pigId tribeId:tribeId] subscribeNext:^(AdoptDetailList * _Nullable adoptDetailList) {
        @strongify(self);
        self.dataModel = adoptDetailList;
        [self.headImgArr addObjectsFromArray:adoptDetailList.maters];
        [self.trusteePriceArr addObjectsFromArray:adoptDetailList.stagePrices];
        
        self.headerView.headerDataArr = self.headImgArr;
        self.headerView.dataModel = self.dataModel;

        [self.myTableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
- (BOOL)isAgreeAdoptAgreement {
    if (!self.footerView.confirmAgreementBtn.selected) {
        [self toastWithContent:@"请阅读并同意领养协议"];
        return NO;
    }
    return YES;
}
#pragma mark - getter and setter

- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]  initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.tableHeaderView = self.headerView;
    }
    return _myTableView;
}
-(PigHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[PigHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 410 + ScaleHeight(240))];
        _headerView.backgroundColor = [UIColor globalBackgroundColor];
    }
    return _headerView;
}
- (NSArray *)leftTitleArr {
    if (!_leftTitleArr) {
        _leftTitleArr = [[NSArray alloc] init];
    }
    return _leftTitleArr;
}

- (NSMutableArray *)headImgArr {
    if (!_headImgArr) {
        _headImgArr = [[NSMutableArray alloc] init];
    }
    return _headImgArr;
}
- (NSMutableArray *)trusteePriceArr {
    if (!_trusteePriceArr) {
        _trusteePriceArr = [[NSMutableArray alloc] init];
    }
    return _trusteePriceArr;
}
- (AdoptDetailList *)dataModel {
    if (!_dataModel) {
        _dataModel = [[AdoptDetailList alloc] init];
    }
    return _dataModel;
}

@end

